package com.exsun.ex1077.ui.fragment.vehiclevideo

import android.app.Activity
import android.graphics.Color
import android.os.Bundle
import android.view.View
import com.amap.api.maps.CameraUpdateFactory
import com.amap.api.maps.model.BitmapDescriptorFactory
import com.amap.api.maps.model.Marker
import com.amap.api.maps.model.MarkerOptions
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.Utils
import com.drake.brv.annotaion.DividerOrientation
import com.drake.brv.utils.divider
import com.drake.brv.utils.grid
import com.drake.brv.utils.setup
import com.exsun.ex1077.R
import com.exsun.ex1077.databinding.FragmentVehicleVideoBinding
import com.exsun.ex1077.network.ApiUrl
import com.exsun.ex1077.network.entity.MapVehicle
import com.exsun.ex1077.network.entity.VehicleTrackSocket
import com.zhangping.amap.AMapHelper
import com.zhangping.amap.LocationHelper
import com.zhangping.amap.extend.getLatLng
import com.zhangping.fastjetpack.base.BaseFragment
import com.zhangping.fastjetpack.binding.visible
import com.zhangping.fastjetpack.extend.*
import com.zhangping.fastjetpack.extend.base.parseState
import com.zhangping.fastjetpack.extend.view.toView
import com.zhangping.fastjetpack.model.Item
import com.zhangping.fastjetpack.network.websocket.WebSocketManager
import kotlinx.android.synthetic.main.fragment_vehicle_video.*
import kotlinx.android.synthetic.main.map_cluster_selected.view.*
import kotlinx.coroutines.Job
import xyz.doikki.videocontroller.StandardVideoController
import xyz.doikki.videoplayer.player.VideoView
import xyz.doikki.videoplayer.player.VideoViewManager

/**
 * 描述：
 * 作者：ZhangPing
 * 创建时间：2022/11/4 15:59
 */
class VehicleVideoFragment : BaseFragment<VehicleVideoViewModel, FragmentVehicleVideoBinding>() {

    override fun layoutId() = R.layout.fragment_vehicle_video

    private lateinit var model: MapVehicle
    /**
     * 当前被选中得通道
     */
    private var currentChannel: String? = ""
    private var vehicleMarker: Marker? = null
    private var videoEnable = false

    /**
     * 是否是由地图立即进入视频播放
     * 如果是则直接播放视频，否则须等到TAB首次切换到视频时再进行播放
     */
    private var videoFirst = false

    /**
     * 视频已经播放过了
     */
    private var videoPlayed = false

    /**
     * 后台5分钟后自动断开连接
     * 用于节约终端设备流量
     */
    var backJob: Job? = null

    /**
     * 断开连接的间隔
     */
    var liveCloseTime = getCacheLong("liveCloseTime", 5 * 60)

    /**
     * 图标名称
     */
    private lateinit var objIcon: String

    override fun initView(savedInstanceState: Bundle?) {
        mDatabind.vm = mViewModel
        super.initView(savedInstanceState)
        model = requireArguments().getSerializable("model") as MapVehicle
        objIcon = model.objIcon
        if (!model.isHasChannel()){
            errorView.visible()
            errorImage.setImageResource(R.drawable.video_error_unsupport)
            return
        }
        if (!model.isOnlineA()){
            errorView.visible()
            errorImage.setImageResource(R.drawable.video_error_offline)
            return
        }
        videoFirst = requireActivity().intent.getBooleanExtra("videoFirst", false)
        videoEnable = true
        contentView.visible()
        //初始化播放器
        videoView.apply {
            setVideoController(StandardVideoController(requireContext()).apply {
                addDefaultControlComponent(model.vehicleNo, true)
            })
            setPlayerBackgroundColor(Color.BLACK)
        }
        //初始化地图
        mapView.onCreate(savedInstanceState)
        mapView.map.uiSettings.apply {
            //不要自带缩放按钮，不要手势旋转，不要自带定位按钮，不要倾斜手势
            isZoomControlsEnabled = false
            isRotateGesturesEnabled = false
            isMyLocationButtonEnabled = false
            isTiltGesturesEnabled = false
            setLogoBottomMargin(-100)
        }
        LocationHelper.myLocation?.let {
            mapView.map.moveCamera(CameraUpdateFactory.newLatLng(it.getLatLng()))
        }
        //初始化视频播放通道
        val channelData = model.channels.split(",").mapIndexed { index, text -> Item(text, "通道${text}", checked = index == 0) }
        channelList.grid(4).divider {
            orientation = DividerOrientation.GRID
            setDivider(16, true)
        }.setup {
            addType<Item>(R.layout.list_item_video_channel)
            onClick(R.id.itemRoot) {
                val model = getModel<Item>()
                if (model.id == currentChannel) return@onClick
                //切换播放通道
                models?.forEachIndexed { index, item ->
                    item as Item
                    item.checked = index == modelPosition
                }
                notifyDataSetChanged()
                //开始播放
                startPlay(model.id)
            }
        }.models = channelData

        mViewModel.loadVehicleData(model.dvo)
        if (videoFirst) startPlay()

        AppUtils.registerAppStatusChangedListener(onAppStatusChangedListener)
    }

    private val onAppStatusChangedListener = object : Utils.OnAppStatusChangedListener{
        override fun onForeground(activity: Activity) {
            "APP回到前台".logD()
            backJob?.cancel()
            if (videoView.currentPlayState == VideoView.STATE_IDLE){
                "APP回到前台了，重新开视播放".logD()
                startPlay(currentChannel)
            }
        }

        override fun onBackground(activity: Activity) {
            "APP后台了".logD()
            backJob?.cancel()
            backJob = globalPostDelayed(liveCloseTime * 1000){
                "APP后台了${liveCloseTime}秒，主动断开视频连接".logD()
                activity.runOnUiThread { videoView?.release() }
            }
        }
    }

    /**
     * 开始播放
     */
    private fun startPlay(channel: String? = ""){
        videoPlayed = true
        currentChannel = channel
        if (currentChannel.isNullOrEmpty()){
            currentChannel = model.channels.split(",")[0]
        }
        //释放之前的视频
        videoView.release()
        videoView.apply {
            setUrl(getVideoPlayUrl().apply {
                this.logI("视频播放地址：")
            })
            start()
        }
    }

    /**
     * 组装视频播放地址
     */
    private fun getVideoPlayUrl(): String{
        return "${ApiUrl.VIDEO_URL + model.dvo}_${currentChannel}.media"
    }

    override fun createObserver() {
        super.createObserver()
        mViewModel.mapVehicleGpsResult.observe(this@VehicleVideoFragment){
            parseState(it, {
                it?.let {
                    //移动地图到目标位置
                    mapView.map.moveCamera(CameraUpdateFactory.newLatLngZoom(it.getLatLng(), AMapHelper.MAP_LEVEL_DEFAULT))
                    //添加车辆图标
                    val view = R.layout.map_cluster_selected.toView()
                    view.iv_arrow.setImageResource(if (it.isOnline > 0) R.drawable.cluster_direction_online else R.drawable.cluster_direction_offline)
                    view.iv_bg.setImageResource(if (it.isOnline > 0) R.drawable.cluster_online else R.drawable.cluster_offline)
                    view.iv_bg.setImageResource("object_${objIcon}".toDrawableId())
                    view.iv_arrow.rotation = it.dre.toFloat()
                    vehicleMarker?.remove()
                    vehicleMarker = mapView.map.addMarker(
                        MarkerOptions()
                            .anchor(0.5F,0.5F)
                            .position(it.getLatLng())
                            .icon(BitmapDescriptorFactory.fromView(view))
                    )
                }
            })
        }
        WebSocketManager.apply {
            dataLiveData.observeInFragment(this@VehicleVideoFragment){
                if (!isResumed || !videoEnable || it.isNullOrEmpty()) return@observeInFragment
                val socketModel = it.toModel<VehicleTrackSocket>() ?: return@observeInFragment
                socketModel.wgs84ToGcj02()
                //移动地图到目标位置
                mapView.map.moveCamera(CameraUpdateFactory.newLatLngZoom(socketModel.getLatLng(), AMapHelper.MAP_LEVEL_DEFAULT))
                //添加车辆图标
                val view = R.layout.map_cluster_selected.toView()
                view.iv_bg.setImageResource("object_${objIcon}".toDrawableId())
                view.iv_arrow.rotation = socketModel.dre.toFloat()
                vehicleMarker?.remove()
                vehicleMarker = mapView.map.addMarker(
                    MarkerOptions()
                        .anchor(0.5F,0.5F)
                        .position(socketModel.getLatLng())
                        .icon(BitmapDescriptorFactory.fromView(view))
                )
            }
        }
    }

    override fun onResume() {
        super.onResume()
        mapView.onResume()
        videoView.resume()
    }

    override fun onHiddenChanged(hidden: Boolean) {
        if (!videoEnable) return
        //当不是由地图直接进入视频播放，由车辆详情其他Tab页首次切换至视频播放页面时，开始播放视频
        if (!videoFirst && !videoPlayed){
            startPlay()
            return
        }
        //TAB切换时暂停和继续视频
        if (hidden){
            videoView.pause()
        }else{
            videoView.resume()
        }
    }

    override fun onPause() {
        super.onPause()
        mapView.onPause()
        videoView.pause()
    }

    override fun onBackPressed(): Boolean{
        return videoView.onBackPressed()
    }

    override fun onDestroyView() {
        AppUtils.unregisterAppStatusChangedListener(onAppStatusChangedListener)
        mapView.onDestroy()
        videoView.release()
        super.onDestroyView()
    }
}